<template>
  <el-container>
    <basic-crud ref="crudRef" :defaultListParams="{orderBy:'needEndDate',orderMethod:'asc'}" :option="option"
                apiGetListUrl="/mes/mesWorkOrderController/listHasCompleteCount" selectType="multiple多选"
                @selection-change="handleChangeSelect">
      <template #showLevel="{row}">
        <el-tooltip v-if="row.showLevel == 1" class="item" content="已经超期了" effect="dark" placement="top-start">
          <el-icon :size="20" color="red">
            <BellFilled/>
          </el-icon>
        </el-tooltip>
        <el-tooltip v-else-if="row.showLevel == 2" class="item" content="剩余交付时间5天内" effect="dark"
                    placement="top-start">
          <el-icon :size="20" color="orange">
            <BellFilled/>
          </el-icon>
        </el-tooltip>
        <el-tooltip v-else-if="row.showLevel == 3" class="item" content="剩余交付时间5到10天内" effect="dark"
                    placement="top-start">
          <el-icon :size="20" color="yellow">
            <BellFilled/>
          </el-icon>
        </el-tooltip>
        <el-tooltip v-else-if="row.showLevel == 4" class="item" content="交付日期可控" effect="dark" placement="top-start">
          <el-icon :size="20" color="green">
            <BellFilled/>
          </el-icon>
        </el-tooltip>
        <el-tooltip v-else-if="row.showLevel == 5" class="item" content="还未派工" effect="dark" placement="top-start">
          <el-icon :size="20" color="gray">
            <BellFilled/>
          </el-icon>
        </el-tooltip>
        <el-tooltip v-else-if="row.showLevel == 6" class="item" content="已经入库" effect="dark" placement="top-start">
          <el-icon :size="20" color="lightgreen">
            <BellFilled/>
          </el-icon>
        </el-tooltip>
      </template>
      <template #percent="{row}">
        <el-progress :format="formatPercent" :percentage="row.percent" :stroke-width="15" text-inside></el-progress>
      </template>
      <template #menu-left>
        <el-button icon="plus" type="primary" @click="erpAddClickHandler"> ERP新增计划</el-button>
        <el-button icon="plus" type="primary" @click="erpHandClickHandler"> 手动新增计划</el-button>
        <el-button icon="Setting" plain type="primary" @click="addByWorkHandler"> 设置规程</el-button>
        <el-button icon="user" plain type="success" @click="setAssignerHandler"> 产品主管</el-button>
        <el-button icon="FolderChecked" plain type="primary" @click="exportMonth"> 导出计划</el-button>
        <el-button icon="plus" plain type="primary"> 计划补录</el-button>
        <el-button icon="Reading" plain type="primary"> 完成计划</el-button>
        <el-button icon="FolderAdd" plain type="primary"> 导入补录计划</el-button>
        <el-button icon="Setting" plain type="primary"> 多选调整</el-button>
      </template>

      <template #menu>
        <el-button icon="Delete" plain style="color: red" type="text"> 删除</el-button>
        <el-button icon="Setting" plain type="text"> 规程</el-button>
        <el-button icon="Setting" plain type="text"> 调整</el-button>
        <el-button icon="Sunrise" plain type="text"> 替换</el-button>
        <el-button icon="user" plain style="color:#67C23A;" type="text"> 入库</el-button>
        <el-button icon="EditPen" plain type="text"> 调整名称</el-button>
      </template>
    </basic-crud>
    <!-- ERP新增计划 -->
    <select-request-add ref="SelectRequestAddRef" :submitSuccess="handleRefresh"></select-request-add>
    <!-- 手动新增计划 根据产品新增 -->
    <basic-dialog v-model="SelectRequestAddDialog.visible" :autoClose="false"
                  :loading="SelectRequestAddDialog.loading"
                  :submitBtnLoading="SelectRequestAddDialog.submitLoading" title="选择产品新增计划" width="1000"
                  @submit="handleSelectRequestAddSubmit">
      <avue-form ref="formProductRefs" v-model="SelectRequestAddForm" :option="SelectRequestAddFormOption">
        <template #pdmModelName>
          <el-select
              v-model="SelectRequestAddForm.pdmModelName"
              filterable
              placeholder="请输入产品型号"
              @change="gteProduct"
          >
            <el-option
                v-for="item in dicModuName"
                :key="item.code"
                :label="item.code"
                :value="item.code"
            >
            </el-option>
          </el-select>
        </template>
        <template #pdmProductName>
          <el-select
              v-model="SelectRequestAddForm.pdmProductName"
              filterable
              placeholder="请选择产品名称"
          >
            <el-option
                v-for="item in dicProductName"
                :key="item.id"
                :label="`${item.code}#${item.name}`"
                :value="`${item.id}#${item.name}`"
            >
            </el-option>
          </el-select>
        </template>
        <template #files>
          <avue-upload
              v-model="SelectRequestAddForm.files"
              :action="uploadObject.action"
              :headers="uploadObject.headers"
              :propsHttp="uploadObject.propsHttp"
              :upload-after="uploadAfter"
          ></avue-upload>
        </template>
      </avue-form>
    </basic-dialog>
    <!-- 设置规程 -->
    <select-technology ref="SelectTechnologyRef"></select-technology>
    <!-- 设置产品主管 -->
    <BasicCrudUserRefer v-model="userVisible" @submit="handleUserSubmit"></BasicCrudUserRefer>
  </el-container>
</template>

<script setup>
import {getModelName, getProductList, setAssigner} from "../../../apis/generate/productionPlan"
import SelectRequestAdd from './selectRequestAdd.vue';
import {useUserStore} from '@/store/user';
import axios from "axios";
import SelectTechnology from "./selectTechnology.vue";

const {token} = useUserStore();

const option = ref({
  highlightCurrentRow: true,
  size: 'small',
  addBtn: false,
  cellBtn: false,
  editBtn: false,
  delBtn: false,
  viewBtn: false,
  menuWidth: 380,
  column: [
    {
      label: '预警',
      prop: 'showLevel',
      fixed: true,
      align: 'center',
      width: 50
    },
    {
      label: "状态",
      prop: "status",
      width: 90,
      align: 'center',
      slot: true,
      search: true,
      searchType: "select",
      fixed: true,
      display: false,
      multiple: true,
      searchSpan: 4,
      overHidden: false,
      statusShow: true,
      statusTag: true,
      statusTypeMap: {
        Suspended: 'danger',
        Obsoleted: 'info',
        ExecuteFinish: 'success',
        Finish: 'success'
      },
    },
    {
      label: "完工率",
      prop: 'percent',
      width: 70
    },
    {
      label: '计划编号',
      prop: 'sourceCode',
      minWidth: 200,
      fixed: true,
      search: true,
      searchSpan: 4,
      //searchLabelWidth:'100px',
      overHidden: true,
    },
    {
      label: "erp计划名称",
      prop: "planAuditOrderName",
      display: false,
      overHidden: true,
      fixed: true,
      width: 120,
    },
    {
      label: "项目号",
      prop: "code",
      fixed: true,
      sortable: true,
      display: false,
      width: 130,
      overHidden: true,
      searchSpan: 4,
      search: true,
    },
    {
      label: '数量',
      prop: 'quantity',
      width: 60,
      display: false
    },
    {
      label: "产品名称",
      prop: "pdmProductName",
      sortable: true,
      searchSpan: 4,
      display: false,
      overHidden: true,
      minWidth: 200,
    },
    {
      label: "产品型号",
      prop: "modelName",
      sortable: true,
      overHidden: true,
      width: 120,
      searchSpan: 4,
      display: false,
      search: true,
      formatter: (val) => {
        return val.modelName;
      }
    },
    {
      label: "产品编号",
      prop: "pdmProductCode",
      sortable: true,
      overHidden: true,
      cell: true,
      display: false,
      minWidth: 150,
      searchSpan: 4,
      search: true,
    },
    {
      label: '产品主管',
      prop: 'assignerName',
      width: 100,
      search: true,
      searchSpan: 4,
      display: false
    },
    {
      label: "规程编号",
      prop: "primaryTargetCode",
      width: 120,
      overHidden: true,
      search: true,
      sortable: true,
      searchSpan: 4,
      display: false,
      slot: true,
      formatter: (val) => {
        if (val.targets && val.targets.length > 0) {
          var s = "";
          for (var i = 0; i < val.targets; i++) {
            var record = val.targets[i];
            s += record.targetCode + " " + record.targetName;
            if (i != val.targets.length - 1) {
              s += "<br/>";
            }
          }
          return s;
        } else {
          return val.primaryTargetCode;
        }
      },
    },
    {
      label: "计划开始日期",
      prop: "needStartDate",
      sortable: true,
      width: 120,
      display: false,
      formatter: (row) => {
        return row.needStartDate?.substring(0, 10);
      },
    },
    {
      label: "计划结束日期",
      prop: "needEndDate",
      sortable: true,
      width: 120,
      display: false,
      search: true,
      searchSpan: 8,
      //searchLabelWidth:'100px',
      searchType: 'daterange',
      formatter: (row) => {
        return row.needEndDate?.substring(0, 10);
      },
    },
    {
      label: "计划交付日期",
      prop: "deliveryDate",
      sortable: true,
      display: false,
      width: 120,
      formatter: (row) => {
        return row.deliveryDate?.substring(0, 10);
      },
    },
    {
      label: "开工日期",
      prop: "beginDate",
      sortable: true,
      display: false,
      width: 120,
      formatter: (row) => {
        return row.beginDate?.substring(0, 10);
      },
    },
    {
      label: "完工日期",
      prop: "finishDate",
      sortable: true,
      display: false,
      width: 120,
      formatter: (row) => {
        return row.finishDate?.substring(0, 10);
      },
    },
    {
      label: "入库日期",
      prop: "realDeliveryDate",
      sortable: true,
      display: false,
      width: 120,
      formatter: (row) => {
        return row.realDeliveryDate?.substring(0, 10);
      },
    },
    {
      label: "紧急程度",
      prop: "exigencyLevel",
      display: false,
      width: 80,
      type: "select",
      dicData: [
        {
          label: "不紧急",
          value: "none",
        },
        {
          label: "一般",
          value: "normal",
        },
        {
          label: "紧急",
          value: "exigency",
        },
        {
          label: "非常紧急",
          value: "veryExigency",
        },
      ],
      formatter: (val) => {
        return val.exigencyLevelText;
      },
    },
    {
      label: "军检",
      prop: "armyCheck",
      display: false,
      width: 60,
      type: "switch",
      dicData: [{
        label: '否',
        value: 'false'
      }, {
        label: '是',
        value: 'true'
      }],
    },
    {
      label: "批次号",
      prop: "batchNum",
      display: false,
      overHidden: true,
      width: 120,
    },
    {
      label: '配套机型',
      prop: 'targetModel',
      display: false,
      overHidden: true,
      width: 120
    },
    {
      label: "手动计划依据",
      prop: "sourceBasis",
      display: false,
      slot: true,
      width: 120,
    }
  ]
});
const formatPercent = (percent) => {
  if (!percent) {
    return '0.0%';
  }
  return `${percent}%`;
}

//刷新列表
const handleRefresh = () => {
  crudRef.value.getList();
};
const SelectRequestAddRef = ref(null);

// erp新增计划
const erpAddClickHandler = () => {
  SelectRequestAddRef.value.openDialog();
};

// 手动新增计划表单
const formProductRefs = ref(null)
// 手动新增计划弹窗
const SelectRequestAddDialog = ref({
  loading: false,
  submitLoading: false,
  visible: false
});
const SelectRequestAddForm = ref({});
const SelectRequestAddFormOption = ref({
  menuBtn: false,
  submitBtn: false,
  emptyBtn: false,
  labelWidth: 120,
  column: [
    {
      label: "计划编号",
      prop: "sourceCode",
      type: "input",
      gutter: 32,
      span: 12,
      labelWidth: "140",
      rules: [
        {
          required: true,
          message: "请输入计划编号",
          trigger: "blur",
        },
      ],
    },
    {
      label: "项目号",
      prop: "code",
      type: "input",
      gutter: 32,
      span: 12,
      labelWidth: "140",
      rules: [
        {
          required: true,
          message: "请输入项目号",
          trigger: "blur",
        },
      ],
    },
    {
      label: "数量",
      prop: "quantity",
      type: "number",
      labelWidth: "140",
      gutter: 32,
      span: 12,
      rules: [
        {
          required: true,
          message: "请输入数量",
          trigger: "blur",
          type: "number",
        },
      ],
    },
    {
      label: "型号",
      prop: "pdmModelName",
      type: "select",
      labelWidth: "140",
      formslot: true,
      rules: [
        {
          required: true,
          message: "型号不能为空",
          trigger: "blur",
        },
      ],
    },
    {
      label: "产品名称",
      prop: "pdmProductName",
      labelWidth: "140",
      formslot: true,
      rules: [
        {
          required: true,
          message: "产品名称不能为空",
          trigger: "blur",
        },
      ],
    },
    {
      label: "军检",
      prop: "armyCheck",
      labelWidth: "140",
      width: 90,
      type: "switch",
      dicData: [{
        label: '否',
        value: 'false'
      }, {
        label: '是',
        value: 'true'
      }],
      value: 'false'
    },
    {
      label: "计划日期",
      prop: "needDate",
      type: "datetimerange",
      labelWidth: "140",
      format: "yyyy-MM-dd",
      span: 24,
      defaultTime: ["00:00:00", "23:59:59"],
      rules: [
        {
          required: true,
          message: "请选择计划日期",
          trigger: "blur",
        },
      ],
      startPlaceholder: "计划开始日期",
      endPlaceholder: "计划结束日期",
    },
    {
      label: "计划交付日期",
      prop: "deliveryDate",
      labelWidth: "140",
      type: "date",
      rules: [
        {
          required: true,
          message: "请选择计划交付日期",
          trigger: "blur",
        },
      ],
    },
    {
      label: "配套机型",
      prop: "targetModel",
      labelWidth: "140",
      component: 'BasicCrudTableSelect',
      dataType: 'dept',
      width: 150,
      comProps: {
        saveFieldMap: {targetModel: 'name', deptId2: 'id'},
        comType: 'form',
      },
      crudProps: {
        apiReferUrl: '/org/deptController/referGrid',
        options: {
          menu: false,
          columns: [
            {prop: 'name', label: '部门名称'},
            {prop: 'id', label: '部门ID'}
          ]
        }
      },
      curForm: SelectRequestAddForm,
      change: (newV) => {
        SelectRequestAddForm.value = newV;
        formProductRefs.value?.clearValidate();
      },
      rules: [
        {
          required: true,
          message: "请选择配套机型",
          trigger: "change",
        },
      ],
    },
    {
      label: "审批单编号",
      prop: "planAuditOrderCode",
      type: "input",
      gutter: 32,
      span: 12,
      labelWidth: "140",
    },
    {
      label: "审批单名称",
      prop: "planAuditOrderName",
      type: "input",
      gutter: 32,
      span: 12,
      labelWidth: "140",
    },
    {
      label: '批次号',
      prop: 'batchNum',
      span: 12,
      labelWidth: "140",
      rules: [{
        required: true,
        message: "批次号不能为空",
        trigger: "blur"
      }],
    },
    {
      label: "上传依据",
      prop: "files",
      gutter: 32,
      span: 12,
      type: 'upload',
      labelWidth: "140",
      formslot: true,
      // rules: [
      //   {
      //     required: true,
      //     message: "请选择依据",
      //     trigger: "change",
      //   },
      // ],
    },
  ]
});

const dicModuName = ref([]);
const uploadObject = ref({
  propsHttp: {
    res: "obj",
    name: "obj.name",
    url: "fileViewUrl",
  },
  headers: {
    'h-authorization-token': token
  },
  action: '/API/mes/fileController/uploadFile',
})
const dicProductName = ref([]);
// 手动新增计划
const erpHandClickHandler = () => {
  SelectRequestAddDialog.value.visible = true;
  getModelName({orderMethod: 'asc', orderBy: 'code'}).then((data) => {
    console.log(data);
    dicModuName.value = data;
  }).catch(() => this.$message.error("查询产品信息失败"));

  getProductList().then((data) => {
    dicProductName.value = data;
  });
};

//手动新增计划保存
const handleSelectRequestAddSubmit = () => {
  SelectRequestAddDialog.submitLoading.value = true

  if (!SelectRequestAddForm.value.pdmProductName || SelectRequestAddForm.value.pdmProductName == null) {
    this.$message.error("没有选择产品，不能保存");
    return false;
  }
  let productName = SelectRequestAddForm.value.pdmProductName;
  SelectRequestAddForm.value.needStartDate = formatDate(SelectRequestAddForm.value.needDate[0], "yyyy-MM-dd");
  SelectRequestAddForm.value.needEndDate = formatDate(SelectRequestAddForm.value.needDate[1], "yyyy-MM-dd");
  SelectRequestAddForm.value.deliveryDate = formatDate(SelectRequestAddForm.value.deliveryDate, "yyyy-MM-dd");
  SelectRequestAddForm.value.pdmProductName = productName.split("#")[1];
  formProductRefs.value.validate((validate, done) => {
    if (validate) {
      delete SelectRequestAddForm.value["files"];
      SelectRequestAddForm.value.onlyProduct = true;
    }
  });
}
const crudRef = ref(null)

const selectList = ref([]);
const workOrderId = ref(null);
const handleChangeSelect = (row) => {
  selectList.value = row;
  workOrderId.value = row.map((item) => item.id).toString();
}

const SelectTechnologyRef = ref(null);
// 设置规程
const addByWorkHandler = () => {
  if (!selectList.value || selectList.value.length == 0) {
    ElMessage.error("没有选择计划条目，无法设置规程");
    return false;
  }

  var productId = "";
  var hasIndex = 0;
  var notEqual = false;
  for (let i = 0; i < selectList.value.length; i++) {
    var record = selectList.value[i];
    if (productId == "") {
      productId = record.pdmProduct;
    } else {
      if (productId != record.pdmProduct) {
        ElMessage.error(
            "只有计划关联的产品相同的时候才能批量设置规程，请先查证"
        );
        notEqual = true;
        break;
      }
    }
    if (record.primaryTargetId != null && record.primaryTargetId != "") {
      hasIndex++;
    }
  }
  if (notEqual) {
    return;
  }
  if (hasIndex > 0) {
    ElMessageBox.confirm(
        `有` +
        hasIndex +
        `条计划已经添加了规程，如果要替换请点击右侧的【查看或替换规程】；如果确实需要继续添加规程，请点击【确定】`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    ).then(() => {
      console.log(123)
      let params = {
        productCode: selectList.value[0].modelName,
        primaryTargetId: selectList.value[0].primaryTargetId || "",
        workOrderId: workOrderId.value,
      };
      SelectTechnologyRef.value.openDialog(params);
    });
  } else {
    let params = {
      productCode: selectList.value[0].modelName,
      primaryTargetId: selectList.value[0].primaryTargetId || "",
      workOrderId: workOrderId.value,
    };
    SelectTechnologyRef.value.openDialog(params);
  }
};

const userVisible = ref(null);
// 设置产品主管
const setAssignerHandler = () => {
  if (!selectList.value || selectList.value.length == 0) {
    ElMessage.error("没有选择计划条目，无法设置负责人");
    return false;
  }
  //校验是否可以设置，当加工完成和入库等状态的时候，不能再执行
  let cannotEdit = selectList.value.find((item) => (item.status == 'ExecuteFinish' || item.status == 'Finish'));
  if (cannotEdit) {
    ElMessage.error("计划的状态是加工完成和已入库的时候，不能再修改");
    return false;
  }
  userVisible.value = true;
};
// 设置产品主管保存
const handleUserSubmit = (data) => {
  console.log(data);
  const submitData = {
    id: data.map((val) => val.id).join(","),
    assigner: data[0].id
  };
  setAssigner(submitData).then((res) => {
    ElMessage.success("设置产品主管成功");
    handleRefresh();
  });
};
// 导出计划
const exportMonth = () => {
  ElMessageBox.confirm(
      '是否导出本月的计划',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    axios({
      method: "get",
      url: "/API/mes/mesWorkOrderController/exportMonth",
      responseType: "blob",
      headers: {
        "Content-Type": "application/json;application/octet-stream",
        "h-authorization-token": token,
      },
    }).then((res) => {
      let fileName = window.decodeURI(
          res.headers["content-disposition"].split(";")[1].split("=")[1],
          "UTF-8"
      ); //获取压缩包文件名称
      let blob = new Blob([res.data], {type: "application/zip"});
      let url = window.URL.createObjectURL(blob);
      const link = document.createElement("a"); // 创建a标签
      link.href = url;
      link.download = fileName; // 重命名文件
      link.click();
      URL.revokeObjectURL(url); // 释放内存
    });
  });
};
</script>

<style lang="scss" scoped>

</style>
